package com.jmlee.service.impl;

import com.jmlee.mapper.UserAddressMapper;
import com.jmlee.mapper.UsersMapper;
import com.jmlee.pojo.UserAddress;
import com.jmlee.pojo.Users;
import com.jmlee.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @Author jmLee
 * @Date 2021/3/1 23:35
 * @Version 1.0
 */
@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Override
    public Users getUserById(Long id) {

        return usersMapper.selectUserById(id);
    }

    @Transactional
    @Override
    public Long addUser(Users user) {

        Users users = usersMapper.selectUserByOpenId(user.getOpenid());
        // 用户不存在，插入数据库
        if (users == null) {
            usersMapper.insertUser(user);
            return user.getId();
        }
        // 用户已注册，直接返回userId
        return users.getId();
    }


    @Override
    public List<UserAddress> getUserAddresses(Long userId) {

        List<UserAddress> userAddresses = userAddressMapper.selectAllAddressById(userId);

        return userAddresses;
    }
}
